#coding:utf-8

import time,os,uuid,json,sys
from app import db
from app.admin import admin
from flask import request, jsonify,session,g,current_app
from werkzeug.utils import secure_filename
from app.models import Goods,User,Order,GoodsSort,GoodsImg,Tables
from app.func.token_auth import auth as http_auth
from response_code import RET
from error_msg import LoggerError

#--------------------------商品后台接口----------------------------------------
# sys._getframe().f_code.co_name   获取本行所在的函数名

#商品标签类型接口
@admin.route("/add_goods_sort",methods=["POST"])
@http_auth.login_required
def add_goods_sort():
    if not g.user_id:
        current_app.logger.error(LoggerError.AUTHERROR)
        return jsonify(code=RET.REQERR,msg="无权请求此接口",data="")
    goods_sort=request.get_json().get("goods_sort")
    if not goods_sort:
        current_app.logger.error(LoggerError.PARAMERROR)
        return jsonify(code=RET.PARAMERR, msg="参数错误")
    try:
        goods_sorts=db.session.query(GoodsSort).filter(GoodsSort.sort==goods_sort).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR, msg="查询数据失败", data="")
    if goods_sorts:
        if goods_sorts.is_del==1:
            goods_sorts.is_del=0
            try:
                db.session.commit()
            except Exception as e:
                current_app.logger.error(e)
                return jsonify(code=RET.DBERR, msg="添加商品分类失败", data="")
            return jsonify(code=RET.OK, msg="添加商品分类成功", data="")
    if not goods_sorts:
        sort=GoodsSort(
            sort=goods_sort,
            addtime=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
        try:
            db.session.add(sort)
            db.session.commit()  # 提交
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(code=RET.DBERR, msg="添加商品分类失败", data="")
        return jsonify(code=RET.OK, msg="添加商品分类成功", data="")

       


#商品标签类型接口
@admin.route("/get_goods_sort",methods=["POST"])
@http_auth.login_required
def get_goods_sort():
    if not g.user_id:
        current_app.logger.error(LoggerError.AUTHERROR)
        return jsonify(code=RET.REQERR,msg="无权请求此接口",data="")
    page=int(request.get_json().get("page"))
    per_page=int(request.get_json().get("per_page"))
    # print(page,per_page)
    try:
        goods_sorts = db.session.query(GoodsSort.id,GoodsSort.sort,GoodsSort.addtime).filter(GoodsSort.is_del==0).paginate(
            page, per_page, error_out=False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR,msg="查询数据失败",data="")
    goods_sort_data = {
        "current_page": goods_sorts.page,
        "pages": goods_sorts.pages,  # 总页数
        "goods_total": goods_sorts.total,  # 数据的总条数
        "goods_list": [{
            "id":goods_sort.id,
            "name":goods_sort.sort,
            "date":str(goods_sort.addtime)
        } for goods_sort in goods_sorts.items]
    }
    return jsonify(code=RET.OK,msg="获取商品分类数据成功",goods_sort=goods_sort_data)

#修改商品标签类型接口
@admin.route("/change_goods_sort",methods=["POST"])
@http_auth.login_required
def change_goods_sort():
    if not g.user_id:
        current_app.logger.error(LoggerError.AUTHERROR)
        return jsonify(code=RET.REQERR,msg="无权请求此接口",data="")
    goods_sort=request.get_json().get("goods_sort")
    new_goods_sort=request.get_json().get("new_goods_sort")
    if not all([goods_sort,new_goods_sort]):
        current_app.logger.error(LoggerError.PARAMERROR)
        return jsonify(code=RET.PARAMERR, msg="参数错误")
    try:
        goods_sorts=db.session.query(GoodsSort).filter(GoodsSort.sort==goods_sort,GoodsSort.is_del==0).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR, msg="查询数据失败", data="")
    if not goods_sorts:
        current_app.logger.error(LoggerError.NODATA)
        return jsonify(code=RET.NODATA,msg="没有查询到数据",data="")
    goods_sorts.sort=new_goods_sort
    try:
        db.session.commit()  # 提交修改
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR, msg="修改商品分类失败", data="")
    return jsonify(code=RET.OK, msg="修改商品分类成功", data="")


#删除商品标签(软删除)
@admin.route("/del_goods_sort",methods=["POST"])
@http_auth.login_required
def del_goods_sort():
    if not g.user_id:
        current_app.logger.error(LoggerError.AUTHERROR)
        return jsonify(code=RET.REQERR,msg="无权请求此接口",data="")
    goods_sort=request.get_json().get("goods_sort")
    if not goods_sort:
        current_app.logger.error(LoggerError.PARAMERROR)
        return jsonify(code=RET.PARAMERR, msg="参数错误")
    print(goods_sort)
    try:
        goods_sorts=db.session.query(GoodsSort).filter(GoodsSort.sort==goods_sort,GoodsSort.is_del==0).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR, msg="查询数据失败", data="")
    if not goods_sorts:
        current_app.logger.error(LoggerError.NODATA)
        return jsonify(code=RET.NODATA,msg="没有查询到数据",data="")
    try:
        goods_sorts.is_del=1
        db.session.commit()  # 提交修改
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR, msg="删除商品分类失败", data="")
    return jsonify(code=RET.OK, msg="删除商品分类成功", data="")


#显示添加的所有商品
@admin.route("/goods",methods=["POST"])
@http_auth.login_required
def show_goods():
    if not g.user_id:
        current_app.logger.error(sys._getframe().f_code.co_name)
        return jsonify(code=RET.REQERR,msg="无权请求此接口",data="")
    user_id =g.user_id
    try:
        goods=db.session.query(Goods.id,Goods.sort,Goods.name,Goods.kucun,Goods.sell_num,Goods.danjia).filter(User.id==user_id).all()    
    except:
        current_app.logger.error(sys._getframe().f_code.co_name)
        return jsonify(code=RET.DBERR,msg="数据库查询失败",data="")
    return jsonify(code=RET.OK,msg="获取商品列表成功",data=goods)

#添加商品
@admin.route("/add_goods",methods=["POST"])
@http_auth.login_required
def add_goods():
    if not g.user_id:
        current_app.logger.error(sys._getframe().f_code.co_name)
        return jsonify(code=RET.REQERR,msg="无权请求此接口",data="")
    user_id =g.user_id
    req_data=request.get_json()
    sort=req_data.get("sort")     #分类
    name=req_data.get("name")   #商品名称
    danjia=req_data.get("danjia")   #单价
    kucun=req_data.get("kucun")   #库存
    sell_num=req_data.get("sell_num")   #销量
    miaoshu=req_data.get("miaoshu")   #商品描述
    if not all([sort,name,danjia,kucun,sell_num,miaoshu]):
        current_app.logger.error(sys._getframe().f_code.co_name)
        return jsonify(code=RET.PARAMERR,msg="参数不完整")
    try:
        goods_data=db.session.query(Goods).filter(Goods.name==name,User.id==user_id).first()
    except:
        current_app.logger.error(sys._getframe().f_code.co_name)
        return jsonify(code=RET.DBERR,msg="查询数据库失败",data="")
    if goods_data:
        current_app.logger.error(sys._getframe().f_code.co_name)
        return jsonify(code=RET.DATAEXIST,msg="商品已存在",data="")
    goods = Goods(
        sort=sort, #分类
        name=name, #标题
        danjia=danjia, #单价
        kucun=kucun, #库存
        sell_num=sell_num,   #销量
        miaoshu=miaoshu, #商品描述
        user_id=user_id, #用户id
        addtime=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
    try:
        db.session.add(goods)
        db.session.commit()   #提交商品
        current_app.logger.error(sys._getframe().f_code.co_name)
        return jsonify(code=RET.OK,msg="添加商品成功",data="")
    except:
        db.session.rollback() 
        current_app.logger.error(sys._getframe().f_code.co_name)    
        return jsonify(code=RET.DBERR,msg="查询数据库失败",data="")

#编辑商品
@admin.route("/change_goods",methods=["GET","POST"])
@http_auth.login_required
def change_goods():
    if not g.user_id:
        current_app.logger.error(sys._getframe().f_code.co_name)
        return jsonify(code=RET.REQERR,msg="无权请求此接口",data="")
    user_id =g.user_id
    # print(user_id)
    if request.method=="POST":
        req_data=request.get_json()
        #需要编辑的文章id
        goods_id=req_data.get("goods_id")
        #需要修改的内容
        sort=req_data.get("sort")     #分类
        name=req_data.get("name")   #商品名称
        kucun=req_data.get("kucun")   #商品库存
        sell_num=req_data.get("sell_num")   #商品销量user_id=user_id
        danjia=req_data.get("danjia")   #商品单价
        miaoshu=req_data.get("miaoshu")   #商品描述
        user_id=user_id
        try:
            goods=db.session.query(Goods).filter(Goods.id==goods_id).filter(User.id==user_id).first()
        except:
            current_app.logger.error(sys._getframe().f_code.co_name)
            return jsonify(code=RET.DBERR,msg="查询数据库失败",data="")
        goods.name=name
        goods.sort=sort
        goods.kucun=kucun
        goods.danjia=danjia  
        goods.sell_num=sell_num
        goods.miaoshu=miaoshu
        goods.user_id=user_id
        try:
            db.session.commit()
        except:
            db.session.rollback()     
            current_app.logger.error(sys._getframe().f_code.co_name) 
            return jsonify(code=RET.DBERR,msg="修改商品失败",data="")
        current_app.logger.error(sys._getframe().f_code.co_name)
        return jsonify(code=RET.OK,msg="修改商品成功",data="")
    else:
        #需要编辑的商品id
        goods_id=request.args.get("goods_id")
        try:
            goods=db.session.query(Goods).filter(Goods.id==goods_id,User.id==user_id).first()
        except:
            current_app.logger.error(sys._getframe().f_code.co_name)
            return jsonify(code=RET.DBERR,msg="查询数据库失败",data="")
        if not goods:
            current_app.logger.error(sys._getframe().f_code.co_name)
            return jsonify(code=RET.NODATA,msg="没有查询到此商品")
        goods_data={
           "name" :goods.name,
           "sort":goods.sort,
           "kucun" :goods.kucun,
           "danjia" :goods.danjia,
           "sell_num" :goods.sell_num,
           "miaoshu":goods.miaoshu
        }
        current_app.logger.error(sys._getframe().f_code.co_name)
        return jsonify(code=RET.OK,msg="获取商品数据成功",data=goods_data)
    

#删除商品
@admin.route("/del_goods",methods=["POST"])
@http_auth.login_required
def delete_goods():
    if not g.user_id:
        current_app.logger.error(sys._getframe().f_code.co_name)
        return jsonify(code=RET.REQERR,msg="无权请求此接口",data="")
    user_id =g.user_id
    req_data=request.get_json()
    #需要删除的商品id
    goods_id=req_data.get("goods_id") #需要修改的商品id
    #查询需要修改的商品
    try:
        goods=db.session.query(Goods).filter(Goods.id==goods_id,User.id==user_id).first()
    except:
        current_app.logger.error(sys._getframe().f_code.co_name)
        return jsonify(code=RET.DBERR,msg="查询数据库失败",data="")
    try:
        db.session.delete(goods)
        db.session.commit()
        current_app.logger.error(sys._getframe().f_code.co_name)
        return jsonify(code=RET.OK,msg="删除商品成功",data="")
    except:
        db.session.rollback()
        current_app.logger.error(sys._getframe().f_code.co_name)
        return jsonify(code=RET.DBERR,msg="删除商品失败",data="")

